package com.liohi.controller;

import com.liohi.AllEunm.MyErrorCode;
import com.liohi.Param.R;
import com.liohi.ThreadPool.AppRuntimeEnv;
import com.liohi.entity.*;
import com.liohi.entity.vo.UserLoginVo;
import com.liohi.entity.vo.UserRegisterVo;
import com.liohi.service.*;
import com.liohi.tools.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@CrossOrigin
@RestController
@Api(tags = "用户接口")
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserService userService;

    @Autowired
    private DictionaryService dictionaryService;

    @ApiOperation("用户登录")
    @PostMapping("login")
    public R userLogin(@RequestBody UserLoginVo user){
        return userService.login(user);
    }

    @ApiOperation("登出")
    @PostMapping("logout")
    public R logout(@NotNull HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        User user = AppRuntimeEnv.getContext().getUser();
//        if(user==null){
//            return R.error(MyErrorCode.ERROR_UNLOGIN_USER.getMsg());
//            }
        //清空当前ThreadLocal信息
        AppRuntimeEnv.clearContext();
        return R.ok("已退出");
    }

    @ApiOperation("获取用户信息")
    @GetMapping("info")
    public R userInfo(@NotNull HttpServletRequest httpServletRequest){
        String token = httpServletRequest.getHeader("token");
        String name = userService.getNameByToken(token);
        HashMap map = new  HashMap<String,Object>();
        List<String> paths = userService.getPathsByToken(token);
        String avatar = userService.getAvatarByUserId(JwtUtils.getUserInfoFromToken(token).getUserId());
        map.put("name",name);
        map.put("avatar",avatar);
        map.put("routes",paths);
        return R.ok(map);
    }

    @ApiOperation("判断用户是否存在")
    @GetMapping("isExist")
    public R isExist(@RequestParam String username){
        if(Objects.isNull(userService.getUserByUsername(username))){
            return R.ok("用户名可用");
        }else {
            return R.error(401,"用户名已被注册");
        }
    }

    @ApiOperation("用户角色列表")
    @GetMapping("typeList")
    public R getUserTypeByTypeCode(@RequestParam String typecode){
        List<String> codeNameByTypeCode = dictionaryService.getCodeNameByTypeCode(typecode);
        return R.ok("codeName",codeNameByTypeCode);
    }

    @ApiOperation("注册")
    @PostMapping("register")
    public R register(@RequestBody UserRegisterVo user){
        return userService.insertUser(user);
    }
    


}
